package Bluetooth.find;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Set;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class BluetoothActivity extends Activity {
    /** Called when the activity is first created. */
    
    public static BluetoothAdapter adap = null;
	public static Context mainContext = null;
	public static ArrayList<BluetoothDevice> btDevices = new ArrayList<BluetoothDevice>();
	public static ArrayList<String> devices = new ArrayList<String>();
    
	public static BluetoothDevice btDevice;
	public static InetAddress serveraddress = null;
	public static TextView tv1;
	public static String mode = new String("Bluetooth");
	public static TextView tv;
	
	public static void printing(String s)
	{
		tv.setText(s);
	}
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mainblue);
        adap=BluetoothAdapter.getDefaultAdapter();
         
        //final TextView tv = new TextView(this);
         tv = (TextView) findViewById(R.id.text);
        tv.setText("BLUETOOTH MANAGER");
       //  tv1 = (TextView) findViewById(R.id.text1);
      //  tv1.setText("HI");
       
        //List
        ListView lv = (ListView) findViewById(R.id.mylist);
        final AlertDialog.Builder ipDialog = new AlertDialog.Builder(this);
        //final ArrayList<BluetoothDevice> btDevices = new ArrayList<BluetoothDevice>();
        //final ArrayList<String> devices = new ArrayList<String>();//[] { "Default" };
        
        // lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, R.id.mylist, FRUITS));
        // ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, FRUITS);
        mainContext = getApplicationContext();
        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, devices);
        
        	// Assign adapter to ListView
        	lv.setAdapter(adapter);
        	lv.setOnItemClickListener(new OnItemClickListener() {
        		@Override
        		public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        		{	
        			btDevice = btDevices.get(position);
        		//	Intent myIntent = new Intent(view.getContext(), FileManager.class);
    	        //	startActivityForResult(myIntent, 0);
    	        	String msg="Sir I would like to meet u at 4 o clock";
        			Thread client= new BTClientThread(btDevice,adap,msg,tv);
        			client.start();

        			Toast.makeText(getApplicationContext(), "Click ListItem Number " + position+ " " + devices.get(position), Toast.LENGTH_LONG).show();
        			adap.cancelDiscovery();
        			//DeviceConnect dc = new DeviceConnect(btDevices.get(position), adap, getApplicationContext());
        			
        		}
        		
        		
        	});
        		

        
        
        //Buttons
        Button turnOnButton;
        turnOnButton = (Button)findViewById(R.id.turn_on);
        Button turnOffButton;
        turnOffButton = (Button)findViewById(R.id.turn_off);
        Button scanButton;
        scanButton = (Button)findViewById(R.id.scan);
        Button discButton;
        discButton = (Button)findViewById(R.id.disc);
        Button exitButton;
        exitButton = (Button)findViewById(R.id.exit);
       /* Button wifiButton;
        wifiButton = (Button)findViewById(R.id.wifi);
        Button wifiServerButton;
        wifiServerButton = (Button)findViewById(R.id.wifiServer);
        //Button btButton;*/
        /*btButton = (Button)findViewById(R.id.bt_mngr);
        btButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	//setContentView(R.layout.mainblue);
            		//toastMessage("Bluetooth", Toast.LENGTH_LONG);
            	}
           });*/
        
        //DialogBox for bluetooth off!
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(R.string.dialog_text)
            .setCancelable(false)
            .setTitle(R.string.dialog_title)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id)
                {
                	//dialog.dismiss();
                	while(!adap.isEnabled())
            			adap.enable();
                	//notify();
            		//tv.append("\nBluetooth was disabled now enabled");
                	dialog.dismiss();
                	toastMessage("Bluetooth was disabled now enabled", Toast.LENGTH_LONG);
            		/*Context context = getApplicationContext();
                    CharSequence text = "Bluetooth turned on successfully.";
                    int duration = Toast.LENGTH_LONG;
                    Toast toast = Toast.makeText(context, text, duration);
                    toast.show();*/
                }
            })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
            dialog.dismiss();
            }
        });
        final AlertDialog btAlert = builder.create();
        
        turnOnButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	if(!adap.isEnabled())
            	{	while(!adap.isEnabled())
            			adap.enable();
        			//tv.append("\nBluetooth was disabled now enabled");
            	toastMessage("Bluetooth was disabled now enabled", Toast.LENGTH_LONG);
            	}
            	else
            	{
            		//tv.append("\nBluetooth already turned on");
            		toastMessage("Bluetooth is already turned on", Toast.LENGTH_SHORT);
            	}
            }
           });
        
        turnOffButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	//Intent myIntent = new Intent(v.getContext(), FileManager.class);
             //startActivityForResult(myIntent, 0);
            	if(adap.isEnabled())
            	{	while(adap.isEnabled())
            			adap.disable();
            		//tv.append("\nBluetooth was on now turned off");
            		toastMessage("Bluetooth turned off", Toast.LENGTH_LONG);
            	}
            	else
            	{
            		//tv.append("\nBluetooth already turned off");
            		toastMessage("Bluetooth already turned off", Toast.LENGTH_LONG);
            	}
            }
           });
        
        exitButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	/*if(adap.isEnabled())
            	{
            		adap.disable();
            	}*/
            	finish();
            	System.exit(0);
            }
           });
        
    
        
        discButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	if(!adap.isEnabled())
            	{	btAlert.show();
            	}
            	if(adap.isEnabled())
            	{	//Making discoverable
            		if (!adap.isDiscovering())
            		{
            			Context context = getApplicationContext();
                      CharSequence text = "MAKING YOUR DEVICE DISCOVERABLE";
                      int duration = Toast.LENGTH_SHORT;
                      Toast toast = Toast.makeText(context, text, duration);
                      toast.show();
                      Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                      startActivityForResult(enableBtIntent,0);
            		}
            	Thread btServer = new BTServerThread(tv,adap);
                  btServer.start();
                  tv.setText("server started");
            	}
            }
           });
        
        BroadcastReceiver mReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            //String str="";
            //tv.append("onReceive");
            if(BluetoothDevice.ACTION_FOUND.equals(action)) 
            {     // Get the BluetoothDevice object from the Intent
                   BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                   // Add the name and address to an array adapter to show in a ListView
                   //str+=device.getName() + "\n";
                   devices.add(device.getName());
                   btDevices.add(device);
                   adapter.notifyDataSetChanged();
                   tv.setText("device addded");
            }
            else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action))
            {
            	//tv.append("\nDiscovery Finished");
            	toastMessage("Discovery finished", Toast.LENGTH_SHORT);
                   	//adap.startDiscovery();
            }
            //tv.append(str);
            }};
            IntentFilter found=new IntentFilter(BluetoothDevice.ACTION_FOUND);
            IntentFilter found2=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
            IntentFilter found3=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
       	    registerReceiver(mReceiver,found);
          	registerReceiver(mReceiver,found2);
          	registerReceiver(mReceiver,found3);
        
        scanButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	/*found=new IntentFilter(BluetoothDevice.ACTION_FOUND);
                found2=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
                found3=new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);*/
           	    /*registerReceiver(mReceiver,found);
              	registerReceiver(mReceiver,found2);
              	registerReceiver(mReceiver,found3);*/
            	if(!adap.isEnabled())
            	{	btAlert.show();
            	}
              	if(adap.isEnabled())
              	{
              		//tv.append("\nScanning");
              		while(adap.isDiscovering())
              		{
              		}
              		
              	}
              		toastMessage("Scanning", Toast.LENGTH_LONG);
              		devices.clear();
              		btDevices.clear();
              		/*Set<BluetoothDevice> pairedDevices = adap.getBondedDevices();
              		// If there are paired devices
              		if (pairedDevices.size() > 0) {
              	    // Loop through paired devices
              	    for (BluetoothDevice device : pairedDevices) {
              	        // Add the name and address to an array adapter to show in a ListView
              	    	btDevices.add(device);
              	        devices.add(device.getName());
              	    }
              		adapter.notifyDataSetChanged();
                	
              	}*/
              		adap.startDiscovery();	
            }
           });
        
        if(adap!=null)
        {
        	if(!adap.isEnabled())
        	{        		
        		btAlert.show();        		
        		//Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        		//startActivityForResult(enableBtIntent, 0);
        	}
        	else
        	{
        		adap.disable();
        		while(!adap.isEnabled())
        		{
        			adap.enable();
        		}
        		//tv.append("\nAlready Enabled");
        		toastMessage("Bluetooth already turned on", Toast.LENGTH_LONG);
        	}
        	/*Intent in=new Intent(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        	startActivityForResult(in,0);*/
        }
        else
        {	//tv.setText("Disabled");
        	toastMessage("Bluetooth feature not available", Toast.LENGTH_LONG);
        }
    }
    
    //Toast Message
    public void toastMessage(CharSequence text, int duration)
    {
    	Context context = getApplicationContext();
        //text = "Bluetooth turned on successfully.";
        //duration = Toast.LENGTH_LONG;
        Toast toast = Toast.makeText(context, text, duration);
        toast.show();
    }
}